//
//  UserRecordViewController.m
//  FuncFanc
//
//  Created by careate-hubing on 2020/12/16.
//  Copyright © 2020 huhu. All rights reserved.
//

#import "UserRecordViewController.h"
#import "TZImagePickerController.h"
#import "SLEditImageController.h"

@interface UserRecordViewController ()<UITableViewDelegate ,UITableViewDataSource,TZImagePickerControllerDelegate,UITextFieldDelegate>

@property (nonatomic,strong) UITableView *tableview;

@property (nonatomic,strong) UITextField *nickanmeTF;

@property (nonatomic,strong) UITextField *idNumberTF;

@property (nonatomic,strong) UILabel *genderLab;

@property (nonatomic,strong) UILabel *ageLab;

@property (nonatomic,strong) UILabel *brithDayLab;

@property (nonatomic,strong) UIImageView *icon;

@property (nonatomic,strong) NSArray *titleArray;

@end

@implementation UserRecordViewController

-(NSArray *)titleArray
{
    if (!_titleArray) {
        _titleArray = @[@"昵称",@"身份证号",@"性别",@"年龄",@"生日",@"头像"];
    }
    return _titleArray;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.title = @"用户信息";
    [self createSubviews];
}

-(void)createSubviews
{
    _tableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableview.delegate = self;
    _tableview.dataSource = self;
    [self.view addSubview:_tableview];
    _tableview.tableFooterView = [self createTableviewFooter];
    [_tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.top.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.titleArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    return 50;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([UITableViewCell class])];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NSStringFromClass([UITableViewCell class])];
    }
    cell.textLabel.text = [NSString stringWithFormat:@"%@",self.titleArray[indexPath.row]];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    switch (indexPath.row) {
        case 0:
        {
            if (!_nickanmeTF) {
                _nickanmeTF = [[UITextField alloc]init];
                _nickanmeTF.placeholder = @"请输入昵称";
                [cell.contentView addSubview:_nickanmeTF];
                [_nickanmeTF mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.right.mas_equalTo(-20);
                    make.left.mas_equalTo(120);
                    make.height.equalTo(cell.contentView);
                    make.centerY.equalTo(cell.contentView);
                }];
            }
        }
            break;
        case 1:
        {
            if (!_idNumberTF) {
                _idNumberTF = [[UITextField alloc]init];
                _idNumberTF.placeholder = @"请输入身份证号";
                _idNumberTF.returnKeyType = UIReturnKeyDone;
                _idNumberTF.delegate = self;
                _idNumberTF.keyboardType = UIKeyboardTypeNamePhonePad;
                [cell.contentView addSubview:_idNumberTF];
                [_idNumberTF mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.right.mas_equalTo(-20);
                    make.left.mas_equalTo(120);
                    make.height.equalTo(cell.contentView);
                    make.centerY.equalTo(cell.contentView);
                }];
            }
        }
            break;
        case 2:
        {
            if (!_genderLab) {
                _genderLab = [[UILabel alloc]init];
                _genderLab.text = @"性别";
                _genderLab.textColor = [UIColor lightGrayColor];
                _genderLab.font = [UIFont systemFontOfSize:13];
                [cell.contentView addSubview:_genderLab];
                [_genderLab mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.right.mas_equalTo(-20);
                    make.left.mas_equalTo(120);
                    make.height.equalTo(cell.contentView);
                    make.centerY.equalTo(cell.contentView);
                }];
            }
        }
            break;
        case 3:
        {
            if (!_ageLab) {
                _ageLab = [[UILabel alloc]init];
                _ageLab.text = @"年龄";
                _ageLab.textColor = [UIColor lightGrayColor];
                _ageLab.font = [UIFont systemFontOfSize:13];
                [cell.contentView addSubview:_ageLab];
                [_ageLab mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.right.mas_equalTo(-20);
                    make.left.mas_equalTo(120);
                    make.height.equalTo(cell.contentView);
                    make.centerY.equalTo(cell.contentView);
                }];
            }
        }
            break;
        case 4:
        {
            if (!_brithDayLab) {
                _brithDayLab = [[UILabel alloc]init];
                _brithDayLab.text = @"生日";
                _brithDayLab.textColor = [UIColor lightGrayColor];
                _brithDayLab.font = [UIFont systemFontOfSize:13];
                [cell.contentView addSubview:_brithDayLab];
                [_brithDayLab mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.right.mas_equalTo(-20);
                    make.left.mas_equalTo(120);
                    make.height.equalTo(cell.contentView);
                    make.centerY.equalTo(cell.contentView);
                }];
            }
        }
            break;
        case 5:
        {
            if (!_icon) {
                _icon = [[UIImageView alloc]init];
                [cell.contentView addSubview:_icon];
                [_icon mas_makeConstraints:^(MASConstraintMaker *make) {
//                    make.right.mas_equalTo(-20);
                    make.left.mas_equalTo(120);
                    make.height.equalTo(cell.contentView);
                    make.width.mas_equalTo(cell.contentView.mas_height);
                    make.centerY.equalTo(cell.contentView);
                }];
            }
        }
            break;
       
        default:
            break;
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    __weak typeof(self) ws = self;
    NSString *titleStr = [self.titleArray objectAtIndex:indexPath.row];
    if ([titleStr isEqualToString:@"头像"]) {
        TZImagePickerController *picker = [[TZImagePickerController alloc]initWithMaxImagesCount:1 delegate:self];
        picker.modalPresentationStyle = UIModalPresentationFullScreen;
        picker.allowTakePicture = YES;
//        picker.autoDismiss = NO;
        [picker setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
//            SLEditImageController *imageEdit = [[SLEditImageController alloc]init];
//            imageEdit.modalPresentationStyle = UIModalPresentationFullScreen;
//            imageEdit.image = photos.firstObject;
//            [ws presentViewController:imageEdit animated:NO completion:nil];
            dispatch_async(dispatch_get_main_queue(), ^{
                ws.icon.image = photos.firstObject;
            });
        }];
        [self presentViewController:picker animated:YES completion:nil];
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([textField isEqual:self.idNumberTF])
    {
        if ([string isEqualToString:@""])
        {
            return  YES;
        }
        else
        {
            if (self.idNumberTF.text.length == 17) {
                [self.idNumberTF resignFirstResponder];
                self.idNumberTF.text = [self.idNumberTF.text stringByAppendingString:string];
                [self setUserInfo];
                return  YES;
            }
            else
            {
                return YES;
            }
        }
    }

    if ([string isEqualToString:@"\n"]) {
        if ([textField isEqual:self.idNumberTF])
        {
            if (self.idNumberTF.text.length < 18) {
                return  NO;
            }
            [self.idNumberTF resignFirstResponder];
            [self setUserInfo];
            
        }
        return NO;
    }
    
    
    return YES;
}

-(void)setUserInfo
{
    UserModel *model = [QHCommonTool getUserInfoWithIDNumber:self.idNumberTF.text];
    if (model.gender == 1)
    {
        self.genderLab.text = @"男";
    }
    else if(model.gender == 2)
    {
        self.genderLab.text = @"女";
    }
    else
    {
        self.genderLab.text = @"未知";
    }
    self.brithDayLab.text = [NSString stringWithFormat:@"%@",model.brithDay];
    
    self.ageLab.text = [NSString stringWithFormat:@"%@",model.age];
}

-(UIView *)createTableviewFooter{
    UIView *footer = [[UIView alloc]init];
    footer.frame = CGRectMake(0, 0, ScreenWidth, 120);
    UIButton *submitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [submitBtn setTitle:@"提交" forState:UIControlStateNormal];
    [submitBtn addTarget:self action:@selector(submitBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [submitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [submitBtn setBackgroundImage:[UIImage imageNamed:@"careateBlueBtnBG"] forState:UIControlStateNormal];;
    submitBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [footer addSubview:submitBtn];
    [submitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(footer);
        make.width.mas_equalTo(80);
        make.height.mas_equalTo(30);
    }];
    return footer;
}

-(void)submitBtnClick:(UIButton *)aBtn
{
    UserModel *model = [UserModel new];
    model.nickName = self.nickanmeTF.text;
    model.age = self.ageLab.text;
    model.idNumber = self.idNumberTF.text;
    model.brithDay = self.brithDayLab.text;
    if ([self.genderLab.text isEqualToString:@"男"]) {
        model.gender = 1;
    }else if([self.genderLab.text isEqualToString:@"女"])
    {
        model.gender = 2;
    }
    else
    {
        model.gender = 0;
    }
    if (_icon.image) {
        // 保存头像图片到本地，然后把路径保存在数据库。
        NSString *iconName = [NSString stringWithFormat:@"%@.PNG",model.idNumber];
        NSString *docDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *imageDir = [docDirectory stringByAppendingPathComponent:@"UserImage"];
        NSString *imagePath = [imageDir stringByAppendingPathComponent:iconName];
        NSFileManager *manager = [NSFileManager defaultManager];
        NSError *createErr;
        [manager createDirectoryAtPath:imageDir withIntermediateDirectories:YES attributes:nil error:&createErr];
        if ([manager fileExistsAtPath:imageDir]) {
            NSData *data = UIImagePNGRepresentation(_icon.image);
            NSError *writeErr = nil;
            [data writeToFile:imagePath options:NSDataWritingWithoutOverwriting error:&writeErr];
        }
        model.avatorPath = imagePath;
    }
   
    LKDBHelper *globalHelper = [LKDBHelper getUsingLKDBHelper];
    [globalHelper insertToDB:model];
    [[HUDHelper sharedInstance]loading:@"用户信息保存成功" delay:1.5 execute:nil completion:nil];
    [self.navigationController popViewControllerAnimated:YES];
}



@end
